/**
 *
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━coder-zhouxiongwei
 */
/**
 * Created by zhouxiongwei on 2019.03.28
 */
var crypto = require('crypto');
const CryptoJS = require('crypto-js'); //引用AES源码js
var request = require('request');

(function () {
    //md5加密
    var encryPassword = this.encryPassword = function (password) {
        password = 'lxy2019' + password;
        var md5 = crypto.createHash('md5');
        var pwd = md5.update(password);
        password = md5.digest('hex');
        return password;
    };

    var checkOvertime = this.checkOvertime = function (t) {
        var time = new Date().getTime();
        if (parseInt((time - t) / 1000) > 120) {
            return false;
        } else {
            return true;
        }
    }

    //解密方法
    var Decrypt = this.Decrypt = function (word) {
        const key = CryptoJS.enc.Utf8.parse("llc2019050920aok"); //十六位十六进制数作为密钥
        const iv = CryptoJS.enc.Utf8.parse('1983457286157286'); //十六位十六进制数作为密钥偏移量
        let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
        
        let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        let decrypt = CryptoJS.AES.decrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        
        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        console.log(decryptedStr);
        return decryptedStr.toString();
    }

    var formatTime = this.formatTime = function (str) {
        if (str.indexOf('.000Z') >= 0) {
            str = str.replace(/T/, ' ');
            str = str.replace(/.000Z/, ' ');
            var a1;
            var a2;
            a1 = str.split(' ');
            a2 = a1[1].split(':');
            a2[0] = parseInt(a2[0]) + 8;
            if (a2[0] >= 24) {
                a1[0] = a1[0].split('-');
                a1[0][2] = parseInt(a1[0][2]) + 1;
                a1[0] = a1[0].join('-');
                a2[0] = a2[0] - 24;
                if (a2[0] < 10) {
                    a2[0] = '0' + a2[0];
                }
            }
            a2 = a2.join(':');
            var update_time = a1[0] + ' ' + a2;
            return update_time;
        } else {
            return str;
        }
    };

    var autoCbErrFunction = this.autoCbErrFunction = function (originalCb, newCb) {
        return function (err, result) {
            if (err) {
                console.log(err);
                originalCb(err);
                return;
            }
            newCb(result);
        }
    }

    var paramAll = this.paramAll = function (req) {
        var parameter = {};
        if (req.params) {
            for (var p in req.params) {
                parameter[p] = req.params[p];
            }
        }
        if (req.body) {
            for (var p in req.body) {
                parameter[p] = req.body[p];
            }
        }
        if (req.query) {
            for (var p in req.query) {
                parameter[p] = req.query[p];
            }
        }
        return parameter;
    };

    var baseRequest = this.baseRequest = function (host, path, param, callback) {
        var url = host + path;
        var form = '';
        for (var key in param) {
            form += key + '=' + param[key] + '&';
        }
        var options = {
            url: url,
            method: 'POST',
            form: form
        };
        request(options, function (error, response, body) {
            if (error || !response || response.statusCode != 200 || !body) {
                callback('服务器异常，请稍后重试');
                console.log(error);
                return;
            } else {
                try {
                    body = JSON.parse(body);
                    if (body.status == 200) {
                        callback(null, body.payload);
                        return;
                    }
                    callback(body.err);
                } catch (e) {
                    callback('服务器异常，请稍后重试');
                }
            }
        });
    }

    //返回拼接上sign的请求对象
    var getSortObjByAsciiWithObj = this.getSortObjByAsciiWithObj =  function (obj, secret) {

        var sortArrStr = getSortStrByAsciiWithObj(obj); //组成按字母顺序排序的字符串

        var waitSecretStr = secret + sortArrStr + secret; //使用前后加secret的方式拼接待加密字符串   waitStr="ek93nkdkswWjfetkey=JF201811212112125phone=18605996973score=11time=1545449321396ek93nkdkswWjfet"
        // console.log(waitSecretStr);
        var md5 = crypto.createHash('md5');
        md5.update(waitSecretStr); //waitSign="c51951be9421b1dd93f9938555d71da5"
        var stringSign = md5.digest('hex');
        var sign = stringSign.toLocaleLowerCase(); //sign="c51951be9421b1dd  93f9938555d71da5"
        obj.sign = sign;
        return obj;
    }

    //构造按Ascii码顺序组成的字符串
    function getSortStrByAsciiWithObj(obj) {
        var arr = [];
        for (var key in obj) {
            arr.push(key);
        }
        var sortArr = getsParaFromArr(arr); //返回按字母顺序排序的数组
        var sortArrStr = '';
        sortArr.forEach(function (key) {
            var item = {};
            item[key] = obj[key];
            sortArrStr += key + '=' + obj[key];
        });

        // console.log('sortArrStr = ' + sortArrStr);
        return sortArrStr; //str="key=JF201811212112125phone=18605996973score=11time=1545449321396"
    }

    //传入数组，返回按Ascii码排序的数组
    function getsParaFromArr(sParaTemp) {
        var sPara = [];
        //除去数组中的空值和签名参数
        for (var i1 = 0; i1 < sParaTemp.length; i1++) {
            var value = sParaTemp[i1];
            if (value == null || value == "" || value == "sign") {
                continue;
            }
            sPara.push(value);
        }
        sPara = sPara.sort();
        return sPara;
    }
})();